/*
 * packet.c
 *
 *  Created on: Aug 20, 2024
 *      Author: 31652
 */

#include <ck156_packet.h>



uint32_t packetLen;
uint32_t packetDataLen;
uint8_t packetBuffer[128];

uint8_t* GetPacketBuffer() {
	return packetBuffer;
}

void OnNewData(i_ringbuffer* dataBuf) {
	// STX(1) ADDR(1) CMD(1) Length(1) DATA(n) BCC(1) ETX(1)
	// check STX Length EXT
	uint8_t tmp;
	for (;;) {
		if (dataBuf->size <= 6) {// packet minimum size.
			break;
		}
		tmp = I_Ring_Buffer_GetByte(dataBuf, 0);
		if (tmp != PacketHead) {
			I_Ring_Buffer_Skip(dataBuf, 1);
			continue;
		}
		packetDataLen = I_Ring_Buffer_GetByte(dataBuf, 3);
		packetLen = packetDataLen+6;
		if (dataBuf->capacity < packetLen) {
			//printf("bad packet, too long %ld.\n", packetLen);
			I_Ring_Buffer_Clear(dataBuf); // bad packet length too long
		}
		if (dataBuf->size < packetLen) { // half packet
			break;
		}
		tmp = I_Ring_Buffer_GetByte(dataBuf, packetLen-1);// tail
		if (tmp != PacketTail) {
			I_Ring_Buffer_Skip(dataBuf, packetLen);
			//printf("bad packet tail 0x%02x\n", tmp);
			continue;
		}
		I_Ring_Buffer_ReadBytes(dataBuf, packetBuffer, packetLen);
		OnPacket(packetBuffer, packetDataLen);
	}
}

void SendTxData(uint8_t *data, uint32_t len) {
	OnTx(data, len);
}
